/**
 * Created by pc on 2016/4/20.
 */
var url = require('url');
var crypto = require('crypto');

function md5_f(data) {
    return crypto.createHash("md5").update(data,"utf8").digest("hex").toUpperCase();
}

function _crypto(value){
    var signature=value;
    return md5_f(signature);
};
//生成signature字符串
var asciiSort=function(option){
    var self=this;
    self.arrSort=function(arr){//数组排序
        var nArr=[];
        var aSig="";
        for(var i=0;i<arr.length;i++){
            if(typeof arr[i]=="string"||typeof arr[i]=="number"||typeof arr[i]=="boolean"){
                nArr.push(arr[i]);
            }else if(arr[i] instanceof Array){//如果是数组
                nArr.push(self.arrSort(arr[i]));//继续调数组排序算法
            }else if(arr[i] instanceof Object){//如果是对象
                nArr.push(self.objSort(arr[i]));//调用对象排序算法
            }
        }
        nArr=nArr.sort();
        if(nArr.length==1){//如果长度为一
            aSig="{"+nArr[0]+"}";
        }else if(nArr.length>1){
            for(var k=0;k<nArr.length;k++){
                if(k>=nArr.length-1){
                    aSig+="{"+nArr[k]+"}";
                }else{
                    aSig+="{"+nArr[k]+"}, ";
                }
            }
            aSig="["+aSig+"]";
        }
        return aSig;
    };

    self.objSort=function(obj){//对象排序算法
        var keyAr=[];
        for(key in obj){
            keyAr.push(key);
        }
        keyAr=keyAr.sort();
        var sig="";
        for(var i=0;i<keyAr.length;i++){//过滤掉undefinded\function\null...
            if(obj[keyAr[i]]!=""&& typeof obj[keyAr[i]]=="string"||typeof obj[keyAr[i]]=="number"||typeof obj[keyAr[i]]=="boolean"){
                sig=sig+(keyAr[i]+"="+obj[keyAr[i]].toString())+"&";
            }else if(obj[keyAr[i]]!=""&&(obj[keyAr[i]] instanceof Array)){//如果是数组
                sig=sig+(keyAr[i]+"="+self.arrSort(obj[keyAr[i]])+"&");
            }else if(obj[keyAr[i]]!=""&&(obj[keyAr[i]] instanceof Object)){//如果是对象
                sig=sig+(keyAr[i]+"={"+self.objSort(obj[keyAr[i]])+"}&");
            }
        }
        sig=sig.substring(0,sig.length-1);
        return sig;
    };
    var preams = self.objSort(option);
    if(preams!=""){
        preams+="&";
    }
    return preams;
};
exports.signature = function(option,key){
    var signature=asciiSort(option);
    return _crypto(signature+"key="+key);
};